<script setup lang="ts">
  import { h, ref } from 'vue'
  import { useGetInfoByCode } from '@/services/pages/code'
  import defaultImg from '@/assets/image/default.png'
  import { ElDivider } from 'element-plus'
  import SelectGood from './select-good/index.vue'
  import useGoods from './useGoods'
  import { GetGoodsOrderCreate, TableDataGoodInfoOrderCreate } from './types'
  import { HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'
  import SelectChild from './select-child/SelectChild.vue'
  import { getTreeBySn } from '@/api/code'

  const { codeInfo, getInfoLoading, getInfo } = useGetInfoByCode()
  const {
    goods,
    addGood,
    findGood,
    removeGood,
    clearAllGoods,
    clearAllNoRegisterCodes,
    clearAllRegisterCodes,
  } = useGoods()

  defineOptions({
    name: 'GoodInfoOrderCreate',
  })

  const props = defineProps({
    factoryId: {
      type: String,
      default: () => '',
    },
    userId: {
      type: String,
      default: () => '',
    },
  })

  const emits = defineEmits<{
    (e: 'change-goods'): void
    (e: 'change-user', value: CodeInfoByCode): void
  }>()

  const snCode = ref('')
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })
  const selectGoodDialogVisible = ref(false)
  const getGoodAndUserInfoByCodeLoading = ref(false)

  const getForm = (data) => {
    return {
      code: data.securityCode,
      goodsName: data.name,
      goodsCode: '',
      goodsSpecName: data.specName,
      goodsBrand: '',
      qty: 1,
      img: '',
      buyTime: '',
      name: '',
      phone: '',
      province: '',
      city: '',
      area: '',
      town: '',
      address: '',
      isEmptyLine: false,
      type: data.codeUserRegister ? 1 : 2,
      goodId: data.id,
      goodSpecId: data.specId,
      codeId: data.codeId,
      goodsSpecCode: data.goodCode,
      parentName: '',
      warrantyStartTime: data.warrantyStartTime,
      warrantyEndTime: data.warrantyEndTime,
    }
  }

  /**
   * 条码搜索事件
   */
  const onGetProductAndCustomerInfoByCode = async () => {
    if (!snCode.value) {
      return
    }
    getGoodAndUserInfoByCodeLoading.value = true
    const res = await getTreeBySn(snCode.value)
    await getInfo(snCode.value)
    getGoodAndUserInfoByCodeLoading.value = false
    // await getInfo(snCode.value)
    const data = res.data.data
    if (data && data.id) {
      // const good = findGood(codeInfo.value.goodsId, codeInfo.value.goodsSpecId, codeInfo.value.code)
      // if (good) {
      //   HMessageBox.error(infoTip.order.create.goodIsExist)
      //   return
      // }
      if (data.type == 1) {
        const list = data.child.map((item) => {
          const obj = getForm(item)
          obj.parentName = data.name
          return obj
        })
        childRef.value.open({ list })
      } else {
        const form: any = getForm(data.child[0])
        form.parentName = data.name
        addGood(form)
      }
      emits('change-goods')
      snCode.value = ''
    } else {
      if (codeInfo.value) {
        const good = findGood(
          codeInfo.value.goodsId,
          codeInfo.value.goodsSpecId,
          codeInfo.value.code,
        )
        if (good) {
          HMessageBox.error(infoTip.order.create.goodIsExist)
          return
        }
        addGood({
          code: codeInfo.value.code,
          goodsName: codeInfo.value.goodsName,
          goodsSpecName: codeInfo.value.goodsSpecName,
          goodsBrand: codeInfo.value.goodsBrand,
          qty: 1,
          img: '',
          buyTime: '',
          name: codeInfo.value.name || '',
          phone: codeInfo.value.phone || '',
          province: codeInfo.value.province || '',
          saleModels: '',
          city: codeInfo.value.city || '',
          area: codeInfo.value.area || '',
          town: codeInfo.value.town || '',
          address: codeInfo.value.address || '',
          isEmptyLine: false,
          type: codeInfo.value.userId ? 1 : 2,
          goodId: codeInfo.value.goodsId,
          goodSpecId: codeInfo.value.goodsSpecId,
          codeId: codeInfo.value.id,
          goodsSpecCode: codeInfo.value.goodsCode,
          warrantyDay: codeInfo.value.warrantyDay,
          warrantyStartTime: codeInfo.value.warrantyStartTime || '',
          warrantyEndTime: codeInfo.value.warrantyEndTime || '',
          userId: codeInfo.value.userId || '',
          registerCode: '',
        })
        emits('change-goods')
        snCode.value = ''
      } else {
        HMessageBox.error(infoTip.order.create.noGetCodeInfoByCode)
      }
    }
    emits('change-user', codeInfo.value)
  }

  const handleChangeQty = (index: number) => {
    goods.value[index].qty = Number(goods.value[index].qty.toString().replace(/\D/g, ''))
    if (goods.value[index].qty <= 0) {
      goods.value[index].qty = 1
    }
  }

  const deleteGoods = (goodsId: any, goodSpecId: any, code: any) => {
    removeGood(goodsId, goodSpecId, code)
    emits('change-goods')
  }
  const getRowClassName = (data: { row: TableDataGoodInfoOrderCreate; rowIndex: number }) => {
    if (data.rowIndex === 0) {
      return 'fixed-row'
    }

    return ''
  }

  const childRef = ref()
  const childConfirm = (data) => {
    data.forEach((item) => {
      addGood(item)
      emits('change-goods')
    })
  }

  defineExpose({
    addGood,
    setSelectedGood: (goodList: Array<TableDataGoodInfoOrderCreate>) => {
      goodList.forEach((good) => {
        addGood(good)
      })
    },
    getGoods: () => {
      const result: Array<GetGoodsOrderCreate> = []

      const goodList = goods.value.filter((good) => good.type === 3)
      const registeredCodeList = goods.value.filter((good) => good.type === 1)
      const noRegisterCodeList = goods.value.filter((good) => good.type === 2)

      if (
        goodList.length === 0 &&
        registeredCodeList.length === 0 &&
        noRegisterCodeList.length === 0
      ) {
        return []
      }

      if (registeredCodeList.length > 0) {
        const obj: GetGoodsOrderCreate = {
          type: 1,
          orderGoodsVos: [],
        }
        registeredCodeList.forEach((registeredCode) => {
          if (registeredCode.goodId && registeredCode.goodSpecId) {
            obj.orderGoodsVos.push({
              buyTime: registeredCode.buyTime,
              codeIds: [registeredCode.codeId],
              endTime: '',
              goodsId: registeredCode.goodId,
              goodsSpecId: registeredCode.goodSpecId,
              id: '',
              qty: registeredCode.qty,
              warrantyDay: registeredCode.warrantyDay,
              name: registeredCode.name,
              phone: registeredCode.phone,
              province: registeredCode.province,
              city: registeredCode.city,
              area: registeredCode.area,
              address: registeredCode.address,
              town: registeredCode.town,
              userId: registeredCode.userId,
            })
          }
        })
        result.push(obj)
      }

      if (noRegisterCodeList.length > 0) {
        const obj: GetGoodsOrderCreate = {
          type: 2,
          orderGoodsVos: [],
        }

        noRegisterCodeList.forEach((noRegisterCode) => {
          if (noRegisterCode.goodId && noRegisterCode.goodSpecId) {
            obj.orderGoodsVos.push({
              buyTime: noRegisterCode.buyTime,
              codeIds: noRegisterCode.codeId ? [noRegisterCode.codeId] : [],
              endTime: noRegisterCode.warrantyEndTime,
              goodsId: noRegisterCode.goodId,
              goodsSpecId: noRegisterCode.goodSpecId,
              id: '',
              qty: noRegisterCode.qty,
              warrantyDay: noRegisterCode.warrantyDay,
              name: noRegisterCode.name,
              phone: noRegisterCode.phone,
              province: noRegisterCode.province,
              city: noRegisterCode.city,
              area: noRegisterCode.area,
              address: noRegisterCode.address,
              town: noRegisterCode.town,
              userId: noRegisterCode.userId,
            })
          }
        })

        result.push(obj)
      }

      if (goodList.length > 0) {
        const obj: GetGoodsOrderCreate = {
          type: 3,
          orderGoodsVos: [],
        }

        goodList.forEach((good) => {
          if (good.goodId && good.goodSpecId) {
            obj.orderGoodsVos.push({
              buyTime: good.buyTime,
              codeIds: [],
              endTime: '',
              goodsId: good.goodId,
              goodsSpecId: good.goodSpecId,
              id: '',
              qty: good.qty,
              warrantyDay: good.warrantyDay,
              name: '',
              phone: '',
              province: '',
              city: '',
              area: '',
              address: '',
              town: '',
              userId: '',
            })
          }
        })

        result.push(obj)
      }

      return result
    },
    clear: () => {
      clearAllGoods()
      clearAllNoRegisterCodes()
      clearAllRegisterCodes()
    },
  })
</script>

<template>
  <div v-loading="getInfoLoading" class="good-info-order-create">
    <div class="title">产品列表</div>
    <el-table
      :border="true"
      stripe
      :data="goods"
      scrollbar-always-on
      max-height="350"
      :row-class-name="getRowClassName"
    >
      <!-- 序号 -->
      <el-table-column type="index" width="50" fixed="left" :align="'center'" label="序号" />

      <!-- 条码 -->
      <el-table-column label="条码" prop="code" show-overflow-tooltip width="250" fixed="left">
        <template #default="{ row }">
          <div v-if="row.isEmptyLine">
            <el-input
              v-model.trim="snCode"
              class="sn-code-input"
              placeholder="请输入条码"
              clearable
              @keyup.enter="onGetProductAndCustomerInfoByCode"
            />
            <h-button
              type="primary"
              :loading="getGoodAndUserInfoByCodeLoading"
              @click="onGetProductAndCustomerInfoByCode"
              >搜索</h-button
            >
          </div>
        </template>
      </el-table-column>

      <!-- 资产码 -->
      <!-- <el-table-column label="资产码" width="140" prop="registerCode" show-overflow-tooltip /> -->

      <!-- 产品编号 -->
      <el-table-column label="产品编号" width="140" prop="goodsSpecCode" show-overflow-tooltip />

      <!-- 销售型号 -->
      <el-table-column label="销售型号" width="140" prop="saleModels" show-overflow-tooltip />

      <!-- 产品名称 -->
      <el-table-column label="产品名称" width="140" prop="goodsName" show-overflow-tooltip />

      <!-- 规格 -->
      <el-table-column label="规格" width="140" prop="goodsSpecName" show-overflow-tooltip />

      <!-- 父项 -->
      <!-- <el-table-column
        label="父项"
        width="140"
        prop="parentName"
        show-overflow-tooltip
      ></el-table-column> -->

      <!-- 数量 -->
      <el-table-column label="数量" width="80">
        <template #default="{ row, $index }">
          <template v-if="!row.isEmptyLine">
            <el-input
              v-if="row.type === 3"
              v-model.trim="row.qty"
              maxlength="5"
              @input="handleChangeQty($index)"
            />
            <el-input v-else v-model.trim="row.qty" disabled />
          </template>
        </template>
      </el-table-column>

      <!-- 图片 -->
      <!-- <el-table-column label="图片" width="200">
        <template #default="{ row }">
          <div v-if="row.img" class="pic">
            <h-image
              :width="40"
              :height="25"
              :src="row.img || defaultImg"
              :padding="2"
              :show-del-btn="false"
            />
          </div>
        </template>
      </el-table-column> -->

      <!-- 购买时间 -->
      <!-- <el-table-column label="购买时间" width="170" prop="buyTime">
        <template #default="{ row }">
          <el-date-picker
            v-if="row.type !== 1 && row.type !== 0"
            v-model="row.buyTime"
            style="width: 140px"
            value-format="YYYY-MM-DD"
            type="date"
          ></el-date-picker>
        </template>
      </el-table-column> -->

      <!-- 购买时间 -->
      <el-table-column prop="warrantyStartTime" label="购买时间" width="140" />

      <!-- 质保截止 -->
      <el-table-column prop="warrantyEndTime" label="质保截止" width="140" />

      <!-- 质保周期 -->
      <el-table-column prop="warrantyDay" label="质保周期" width="75" />

      <!-- 登记信息 -->
      <el-table-column label="登记信息" min-width="360" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.name }}&nbsp;{{ row.phone }}&nbsp; {{ row.province }}-{{ row.city }}-{{
            row.area
          }}-{{ row.town }}-{{ row.address }}
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column label="操作" fixed="right" width="75">
        <template #header>
          <h-link @click="selectGoodDialogVisible = true">选择产品</h-link>
        </template>
        <template #default="{ row }">
          <el-space :size="0" :spacer="spacer">
            <h-link
              v-if="!row.isEmptyLine"
              type="error"
              @click="deleteGoods(row.goodId, row.goodSpecId, row.code)"
            >
              删除
            </h-link>
            <!-- <h-link v-if="$index === 0" @click="selectGoodDialogVisible = true">选择产品</h-link> -->
          </el-space>
        </template>
      </el-table-column>
    </el-table>

    <SelectGood
      v-model:visible="selectGoodDialogVisible"
      :factory-id="props.factoryId"
      :user-id="props.userId"
      @change-goods="emits('change-goods')"
    />
    <SelectChild ref="childRef" @confirm="childConfirm" />
  </div>
</template>

<style scoped lang="scss">
  :deep(.fixed-row) {
    position: sticky;
    position: -webkit-sticky;
    top: 0;
    z-index: 3;
  }

  .sn-code-input {
    width: 160px;
    margin-right: 5px;
  }

  .good-info-order-create {
    box-sizing: border-box;
    padding: 0 12px;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    row-gap: 5px;
    height: 100%;

    .title {
      padding-left: 6px;
      border-left: 3px solid $primaryColor;
      font-size: 14px;
      font-weight: bold;
    }
  }

  :deep(.el-table__body-wrapper) {
    .el-scrollbar {
      .el-scrollbar__wrap {
        box-sizing: border-box;
        padding-bottom: 13px;
      }
    }
  }
</style>
